/**
 * https://leetcode-cn.com/problems/3sum/
 * @param {number[]} nums
 * @return {number[][]}
 */
 var threeSum = function(nums) {
    const solutions = [];
    nums.sort((a,b) => a-b);
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] > 0) break;
        if (i > 0 && nums[i] === nums[i - 1]) continue;
        
        let l = i+1;
        let r = nums.length - 1;
        let target = -1 * nums[i];
        while (l < r) {
            if (nums[l] + nums[r] ===  target) {
                while(l < r && nums[r] === nums[r-1]) {
                    r--;
                }
                while(l < r && nums[l] === nums[l+1]) {
                    l++;
                }
                solutions.push([nums[i],nums[l],nums[r]]);
                l++;
                r--;
                continue;
            }
            nums[l] + nums[r] > target
                ? r--
                : l++;
        }
    }
    return solutions;
};